<?php
/**
 * Loader::model('Users')->wishs();
 * Loader::model('Users')->orders();
 * Loader::model('Users')->caravans()
 */
namespace app\common\model;

use think\Model;
use think\Session;
use think\Loader;
use think\Lang;
use think\Request;
use think\Exception;
use app\common\traits\model\TraitModel;

class Users extends Model
{
    protected $autoWriteTimestamp = 'timestamp';
    protected $createTime         = 'created_at';
    protected $updateTime         = 'updated_at';
    protected $table              = 'users';
    protected $error              = '';
    public static $user_info      = null;
    //protected static $loginuser = '';
    
    use TraitModel;

    public function camp()
    {
        return $this->belongsTo('Camps', 'camp_id');
    }

    public function addUser($user_info = [])
    {
        if (true == !$this->checkUser($user_info, ['mobile'])) {
            $user_info['password'] = md5($user_info['password']);
            return self::create($user_info);
        }else {
            return false;
        }   
    }
    /**
     * 校验用户信息是否存在
     * @param  [type] $user_info [description]
     * @param  array  $onlys     [description]
     * @return [type]            [description]
     */
    public function checkUser($user_info, $onlys = [])
    {
        $user_info = $onlys ? array_intersect_key($user_info, array_flip($onlys)) : $user_info;
        if (!empty($user_info)) {
            foreach ($user_info as $key => $data) {
                if (self::get([$key => $data])) {
                    return true;
                }
            }
        }       
        return false;
    }

    /**
     * [getUserInfo description]
     * @param  [type] $where [description]
     * @param  string $field   [description]
     * @return [type]          [description]
     */
    public static function getUserInfo($where, $field = '')
    {
        if (empty($where)) {
            return false;
        }
        if ($userInfo = self::get($where)) {
            Request::instance()->bind('user', $userInfo);
            if ($field) {
                if (isset($userInfo->$field)) {
                    return $userInfo->$field; 
                }
                throw new Exception(Lang::get("Member information field does not exist"), 10001);
            }
            return $userInfo;
        }
        throw new Exception(Lang::get("Member information does not exist"), 10002);
    }

    public static function getLoginUserInfo($field = null)
    {
        if (Request::instance()->user == null) {
            throw new Exception(Lang::get("Member not logged in"), 10004);            
        }
        if ($field) {
            if (isset(Request::instance()->user->$field)) {
                return Request::instance()->user->$field; 
            }
            throw new Exception(Lang::get("Member information field does not exist"), 10001);
        }
        return Request::instance()->user;  
    }
    /**
     * 会员资金
     * @return [type] [description]
     */
    private function capitals()
    {
        return Loader::model('Capitals');
    }

    /**
     * 获取用户资金信息
     * @return [type] [description]
     */
    public function getUserCapitals()
    {
        return $this->capitals()->getCapital();
    }

    /**
     * 获取用户余额
     * @return [type] [description]
     */
    public function getBlance()
    {
        return $this->capitals()->getBlance();
    }

    /**
     * 获取用户积分
     * @return [type] [description]
     */
    public function getIntegral()
    {
        return $this->capitals()->getIntegral();
    }

    /**
     * 会员订单
     * @return [type] [description]
     */
    private function orders()
    {
        return Loader::model('Orders');
    }

    /**
     * 创建订单
     * @param  [type] $caravan_id     [description]
     * @param  [type] $take_car_date  [description]
     * @param  [type] $leave_car_date [description]
     * @return [type]                 [description]
     */
    public function createOrder($caravan_id, $take_car_date, $leave_car_date, $other = [], $check_share = true)
    {
        $order_info = [
            'caravan_id'     => $caravan_id, 
            'take_car_date'  => $take_car_date, 
            'leave_car_date' => $leave_car_date,
        ];
        return $this->orders()->createOrders(array_merge($order_info, $other), $check_share);
    }

    /**
     * 获取订单列表
     * @param  array  $querys [description]
     * @return [type]         [description]
     */
    public function getOrders($querys = [])
    {
        return $this->orders()->getOrders(array_merge($querys, ['order_user_id' => Request::instance()->user->id]));
    }

    /**
     * 获取订单详情
     * @param  [type] $order_no [description]
     * @return [type]           [description]
     */
    public function getOrder($order_no)
    {
        return $this->orders()->getOrderInfo(['number' => $order_no, 'order_user_id' => Request::instance()->user->id]);
    }

    /**
     * 支付订单
     * @param  [type] $order_no [description]
     * @return [type]           [description]
     */
    public function payOrder($order_no)
    {
        return $this->orders()->payOrder(['number' => $order_no, 'order_user_id' => Request::instance()->user->id]);
    }

    /**
     * 取消订单
     * @param  [type] $order_no [description]
     * @param  [type] $remarks  [description]
     * @return [type]           [description]
     */
    public function cancelOrder($order_no, $remarks = null)
    {
        return $this->orders()->getOrderInfo(['number' => $order_no, 'order_user_id' => Request::instance()->user->id])->cancelOrder($remarks);
    }

    public function endOrder($order_no)
    {
        return $this->orders()->orderEnd($order_no);
    }

    /**
     * [caravans description]
     * @return [type] [description]
     */
    private function caravans()
    {
        return Loader::model('\\app\common\\model\\Caravans');
    }

    /**
     * [resourceBind description]
     * @param  [type] $resource_id [description]
     * @return [type]              [description]
     */
    public function resourceBind($resource_id)
    {
        # code...
    }

    /**
     * 获取用户房车
     * @return [type] [description]
     */
    public function getUserCaravans()
    {
        return $this->caravans()->getCaravans(['user_id' => Request::instance()->user->id]);
    }

    /**
     * 获取房车信息
     * @param  [type] $caravan_id [description]
     * @return [type]             [description]
     */
    public function getCaravanInfo($caravan_id)
    {
        return $this->caravans()->getCaravanInfo(['id' => $caravan_id, 'user_id' => Request::instance()->user->id]);
    }

    public function updateCaravanInfo($caravan_id, $infos)
    {
        return $this->caravans()->updateCaravanInfo(['id' => $caravan_id, 'user_id' => Request::instance()->user->id], $infos);
    }

    /**
     * 实例化心愿模型
     * @return [type] [description]
     */
    private function wishs()
    {
        return Loader::model('Wishs');
    }

    /**
     * 创建心愿
     * @param  [type] $wish_info [description]
     * @return [type]            [description]
     */
    public function createWish($wish_info)
    {
        return $this->wishs()->createUserWishs($wish_info);
    }

    /**
     * 获取心愿详情
     * @param  [type] $wish_id [description]
     * @return [type]          [description]
     */
    public function getWishInfo($wish_id)
    {
        return $this->wishs()->getWishInfo($wish_id);
    }

    public function updateWish($wish_id, $wish_info = [])
    {
        return $this->wishs()->updateWish($wish_id, $wish_info);
    }

    /**
     * 获取自己的心愿列表
     * @return [type] [description]
     */
    public function getWishs($querys = [])
    {
        return $this->wishs()->getUserWishs($querys);
    }

    /**
     * 获取可接单心愿
     * @param  array  $where [description]
     * @return [type]        [description]
     */
    public function getOtherUserWishs($where = [], $page)
    {
        return $this->wishs()->getOtherUserWishs($where,$page);
    }

    /**
     * 心愿接单
     * @param  [type] $wish_id [description]
     * @return [type]          [description]
     */
    public function meetWish($caravan_id, $wish_id)
    {
        return $this->wishs()->getWishInfo($wish_id)->meetWish($this->getCaravanInfo($caravan_id));
    }

    /**
     * 完成心愿
     * @param  [type] $wish_id [description]
     * @param  [type] $meet_id [description]
     * @return [type]          [description]
     */
    public function completeWish($wish_id, $meet_id, $other = [])
    {
        return $this->wishs()->getWishInfo($wish_id)->completeWish($meet_id, $other);
    }

    /**
     * 取消发布心愿
     * @param  [type] $wish_id [description]
     * @return [type]          [description]
     */
    public function cancelWishs($wish_id)
    {
        return $this->wishs()->getWishInfo($wish_id)->cancelWishs();
    }

    /**
     * 行程
     * @return [type] [description]
     */
    private function trips()
    {
        return Loader::model('Trips');
    }

    /**
     * 通知
     * @return [type] [description]
     */
    private function notices()
    {
        return Loader::model('Notices');
    }

    /**
     * 获取通知条数（默认未读）
     * @return [type] [description]
     */
    public function getNoticeCount($status)
    {
        return $this->notices()->getNoticeCount($status);
    }

    public function setAllNoticesIsRead()
    {
        return $this->notices()->setAllNoticesIsRead();
    }

    /**
     * 获取通知列表
     * @return [type] [description]
     */
    public function getNoticeList()
    {
        return $this->notices()->getNoticeList();
    }

    /**
     * 读取通知
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function readNotice($id)
    {
        return $this->notices()->readNotice($id);
    }

    /**
     * 删除通知信息
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function delNotice($ids)
    {
        return $this->notices()->delNotice($ids);
    }

    private function cashs()
    {
        return Loader::model('Cashing');
    }

    public function applyWithdraw($amount, $bank_info, $currency = 'CNY')
    {
        return $this->cashs()->apply($amount, $bank_info, $currency);
    }
}
